<template>
  <div class="sysoperationLog">
    <div class="mains_contain">
      <el-form :inline="true" :model="searchForm" size="small" label-width="80px">
        <el-form-item label="接口名称">
          <el-input v-model="searchForm.funcName" clearable placeholder="请输入接口名称" />
        </el-form-item>
        <el-form-item label="方法名称">
          <el-input v-model="searchForm.methodName" clearable placeholder="请输入方法名称" />
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker v-model="valueTimes" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" icon="el-icon-search" size="mini">查询</el-button>
          <el-button type="primary" @click="exportLog" icon="el-icon-download" size="mini">导出</el-button>
        </el-form-item>
      </el-form>

      <div class="contant">
        <el-table :data="tableData" ref="multipleTable" style="width: 100%" @selection-change="handleSelectionChange" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row
          :header-cell-style="{ background: '#e5e5e5', color: '#000' }" :row-key="bindKey">
          <el-table-column type="selection" width="40" :reserve-selection="true" />
          <el-table-column prop="operator" label="操作账号" width="100" />
          <el-table-column prop="userName" label="操作用户名" width="100" />
          <el-table-column prop="ip" label="请求ip" width="120" />
          <el-table-column prop="funcName" label="接口名称" width="200" />
          <el-table-column prop="methodName" label="方法名称" width="200" />
          <el-table-column prop="terminal" label="请求终端" width="100" />
          <el-table-column prop="url" label="请求URL" width="220" />
          <el-table-column prop="results" label="操作结果" width="100">
            <template slot-scope="scope">
              <!-- <el-tag
                type="success"
                effect="dark"
                size="mini"
                v-if="scope.row.results == 200"
                >成功</el-tag
              >
              <el-tag
                type="danger"
                effect="dark"
                size="mini"
                v-if="scope.row.results == 500"
                >异常</el-tag
              > -->
              <span style="color: #67c23a" v-if="scope.row.results == '200'">成功</span>
              <span style="color: #f56c6c" v-if="scope.row.results == '500'">异常</span>
            </template>
          </el-table-column>
          <el-table-column prop="costTime" label="耗时（ms）" width="100" />
          <el-table-column prop="createTime" label="操作时间" width="140">
            <template slot-scope="scope">
              {{ scope.row.createTime | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="180" fixed="right">
            <template slot-scope="{ row }">
              <el-button type="text" size="mini" @click="handleInfo(row)" icon="el-icon-view">详情</el-button>
              <!-- <el-button type="text" size="mini" icon="el-icon-delete" @click="handleDelete(row)" style="color: #f56c6c">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align: right">
          <pagination v-show="pagination.total > 0" :limit.sync="pagination.pageSize" :page.sync="pagination.page" :total="pagination.total" @pagination="getPageList" />
        </div>
      </div>
    </div>
    <el-dialog title="日志详情" :visible.sync="dialogVisible" width="800px" top="5vh" v-dialogDrag>
      <el-form ref="infoForm" :model="infoForm" label-width="120px" size="mini">
        <el-form-item label="操作账号：">{{
          infoForm.operator || "--"
        }}</el-form-item>
        <el-form-item label="操作用户名：">{{
          infoForm.userName || "--"
        }}</el-form-item>
        <el-form-item label="请求ip：">{{ infoForm.ip || "--" }}</el-form-item>
        <el-form-item label="方法名称：">{{
          infoForm.methodName || "--"
        }}</el-form-item>
        <el-form-item label="接口名称：">{{
          infoForm.funcName || "--"
        }}</el-form-item>
        <el-form-item label="请求终端：">{{
          infoForm.terminal || "--"
        }}</el-form-item>
        <el-form-item label="请求URL：">{{
          infoForm.url || "--"
        }}</el-form-item>
        <el-form-item label="请求耗时：">{{
          infoForm.costTime || "--"
        }}</el-form-item>
        <el-form-item label="操作结果：">
          <span v-if="infoForm.results == 200">成功</span>
          <span v-if="infoForm.results == 500">异常</span>
        </el-form-item>
        <el-form-item label="操作时间：">{{
          infoForm.createTime | formatTime
        }}</el-form-item>
        <el-form-item label="请求报文：">
          <el-scrollbar style="height: 100%">
            <json-viewer :value="infoForm.requestData" :expand-depth="4" copyable boxed sort></json-viewer>
          </el-scrollbar>
        </el-form-item>
        <!-- <el-form-item label="响应结果：">
          <el-scrollbar style="height: 100%">
            <json-viewer
              :value="infoForm.responseBody"
              :expand-depth="4"
              copyable
              boxed
              sort
            ></json-viewer>
          </el-scrollbar>
        </el-form-item> -->
        <el-form-item label="响应报文：">
          <el-scrollbar style="height: 100%">
            <json-viewer :value="infoForm.responseData" :expand-depth="2" copyable boxed sort></json-viewer>
          </el-scrollbar>
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button @click="dialogVisible = false" size="small">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import * as api from "@/api/link/sysoperationLog";
import { isJSON } from "@/utils/index";
export default {
  comments: {},
  props: {},
  data() {
    return {
      valueTimes: [],
      tableData: [],
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10,
      },
      dialogVisible: false,
      infoForm: {},
      searchForm: {},
      exportUrl: "/api/sys/v1/operation-log/export",
      checkList: [],
    };
  },
  computed: {
    maxHeight() {
      var curHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight;
      return curHeight - 280;
    },
  },
  created() {
    this.getPageList();
    // this.ready()
  },
  mounted() { },
  methods: {
    bindKey(row) {
      return row.id;
    },
    // ready(){
    //  var cip = returnCitySN["cip"];
    //  console.log(cip);//cip就是本机ip地址
    // },
    handleInfo(row) {
      console.log(row);
      this.dialogVisible = true;
      var curRow = Object.assign({}, row);
      if (isJSON(curRow.body)) {
        curRow.body = JSON.parse(curRow.body);
      } else {
        curRow.body = {};
      }
      if (isJSON(curRow.responseBody)) {
        curRow.responseBody = JSON.parse(curRow.responseBody);
      } else {
        curRow.responseBody = {};
      }
      if (isJSON(curRow.responseData)) {
        curRow.responseData = JSON.parse(curRow.responseData);
      } else {
        curRow.responseData = {};
      }

      this.infoForm = curRow;
    },
    // 复选框事件
    handleSelectionChange(val) {
      console.log(val);
      //   this.multipleSelection = val;
      this.checkList = val;
    },
    getPageList() {
      this.searchList();
    },
    search() {
      this.pagination.page = 1;
      this.searchList();
    },
    searchList() {
      const p = Object.assign({}, this.pagination);
      if (
        this.searchForm.methodName != undefined &&
        this.searchForm.methodName != ""
      ) {
        p.methodName = this.searchForm.methodName;
      }
      if (
        this.searchForm.funcName != undefined &&
        this.searchForm.funcName != ""
      ) {
        p.funcName = this.searchForm.funcName;
      }
      if (this.valueTimes && this.valueTimes.length) {
        p.startTime = this.valueTimes[0];
        p.endTime = this.valueTimes[1];
      } else {
        p.startTime = "";
        p.endTime = "";
      }
      api.page(p).then((resp) => {
        this.tableData = resp.data.list;
        this.pagination = resp.data.pagination;
        this.pagination.page = resp.data.pagination.current;
      });
    },
    //删除
    handleDelete(row) {
      this.$confirm("此操作将永久删除该日志, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.deleteById(row.id).then((resp) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            if ((this.pagination.total - 1) % this.pagination.pageSize == 0) {
              if (this.pagination.page > 1) {
                this.pagination.page = this.pagination.page - 1;
              }
            }
            this.search();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //导出
    //   exportLog() {
    //     // let url = window.location.origin
    //     // window.location.href = url + this.exportUrl + `?funcName=${this.searchForm.funcName?this.searchForm.funcName:''}&&methodName=${this.searchForm.methodName?this.searchForm.methodName:''}&&startTime=${this.valueTimes&&this.valueTimes[0]?this.valueTimes&&this.valueTimes[0]:''}&&endTime=${this.valueTimes&&this.valueTimes[1]?this.valueTimes&&this.valueTimes[1]:''}&&idList=${this.checkList?this.checkList:[]}`
    //  },
    exportLog() {
      let checkListAll = [];
      this.checkList.forEach((item) => {
        checkListAll.push(item.id);
      });
      console.log(checkListAll)
      if (checkListAll.length) {
        if (checkListAll.length > 1000) {
          this.$message({
            type: "warning",
            message: "最多导出1000条数据",
          });
          return;
        }
        let param = {
          ids: checkListAll.join(","),
          funcName: this.searchForm.funcName ? this.searchForm.funcName : "",
          methodName: this.searchForm.methodName
            ? this.searchForm.methodName
            : "",
          startTime:
            this.valueTimes && this.valueTimes[0]
              ? this.valueTimes && this.valueTimes[0]
              : "",
          endTime:
            this.valueTimes && this.valueTimes[1]
              ? this.valueTimes && this.valueTimes[1]
              : ""
        };
        api.exportLog(param).then((res) => {
          const blob = new Blob([res], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          });
          const fileName = "系统操作日志" + ".xlsx";
          if ("download" in document.createElement("a")) {
            // 支持a标签download的浏览器
            const link = document.createElement("a"); // 创建a标签
            link.download = fileName; // a标签添加属性
            link.style.display = "none";
            link.href = URL.createObjectURL(blob);
            document.body.appendChild(link);
            link.click(); // 执行下载
            URL.revokeObjectURL(link.href); // 释放url
            document.body.removeChild(link); // 释放标签
            this.$refs.multipleTable.clearSelection();
          } else {
            // 其他浏览器
            navigator.msSaveBlob(blob, fileName);
          }
        });
        return;
      } else {
        if (this.pagination.total > 1000) {
          this.$message({
            type: "warning",
            message: "最多导出1000条数据",
          });
          return;
        }
      }
    },
  },
};
</script>

<style scoped lang="scss">
.sysoperationLog {
  padding: 20px;

  .curHeader {
    position: relative;
    height: 40px;
    .searcherBox {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
}
</style>



<style lang="scss">
.sysoperationLog {
  .el-form-item--mini .el-form-item__content,
  .el-form-item--mini .el-form-item__label {
    line-height: 15px !important;
  }
}
</style>
